<!--提货卡生成记录-->
<template>
  <div>
    <Card :bordered="false" dis-hover class="mt15 ivu-mt" :padding="0">
      <div class="new_card_pd">
        <Form ref="tableFrom" inline
              :model="tableFrom" :label-width="labelWidth"
              :label-position="labelPosition" @submit.native.prevent>
          <FormItem label="激活状态" label-for="status">
            <Select v-model="tableFrom.active_status" placeholder="请选择" clearable @on-change="userSearchs"
                    style="width: 250px;"
            >
              <Option value="0">未激活</Option>
              <Option value="1">已激活</Option>
            </Select>
          </FormItem>
          <FormItem label="购买单位名称">
            <Input v-model="tableFrom.use_company" placeholder="请输入购买单位名称" style="width: 250px;margin-right:14px"/>
          </FormItem>
          <FormItem label="提货卡开始编号">
            <Input v-model="tableFrom.start_card_no" placeholder="请输入提货卡开始编号Eg：NO.2022000014" style="width: 260px;margin-right:14px" />
          </FormItem>
          <FormItem label="提货卡结束编号">
            <Input v-model="tableFrom.end_card_no" placeholder="请输入提货卡结束编号Eg：NO.2022000014" style="width: 260px;margin-right:14px" />
          </FormItem>
          <FormItem label="序列号">
            <Input v-model="tableFrom.card_serial" placeholder="请输入序列号" style="width: 250px;margin-right:14px"/>
          </FormItem>
          <FormItem label="提货卡名称：" label-for="coupon_title">
            <Input v-model="tableFrom.title" placeholder="请输入提货卡名称" @on-search="userSearchs"
                   style="width: 250px;margin-right:14px"/>
            <Button type="primary" @click="orderSearch()" style="margin-right:14px">查询</Button>
          </FormItem>
        </Form>
      </div>
    </Card>

    <Card :bordered="false" dis-hover class="ivu-mt">
      <Button v-auth="['admin-user-recharcard-create']" type="primary" @click="activeAll" >批量激活提货卡</Button>
      <Button v-auth="['admin-user-recharcard-create']" style="margin-left:20px;" type="primary" @click="exportList" >下载导出</Button>
      <Table :columns="columns1" :data="tableList" ref="table" class="ivu-mt"
             :loading="loading" highlight-row
             no-userFrom-text="暂无数据"
             no-filtered-userFrom-text="暂无筛选结果">
        <template slot-scope="{ row }" slot="recharcard_money">
          <span>{{ row.recharcard_money }}元</span>
          <!-- <span
              v-if="row.coupon_type==2">{{ parseFloat(row.recharcard_money) / 10 }}折（{{ row.recharcard_money.toString().split(".")[0] }}%）</span> -->
        </template>
        <template slot-scope="{ row }" slot="recharcard_img">
          <img style="width:50px;height:50px" :src="row.recharcard_img" alt="">
        </template>
        <template slot-scope="{ row }" slot="count">
          <span v-if="row.is_permanent">不限量</span>
          <div v-else>
            <span class="fa">发布：{{ row.total_count }}</span>
            <span class="sheng">剩余：{{ row.remain_count }}</span>
          </div>
        </template>
        <template slot-scope="{ row }" slot="card_serial">
          <span>{{row.card_serial}}</span>
        </template>
        <template slot-scope="{ row }" slot="recharcard_title">
          <Tooltip max-width="200" placement="bottom">
            <span class="line2">{{ row.recharcard_title }}</span>
            <p slot="content">{{ row.recharcard_title }}</p>
          </Tooltip>
        </template>
        <template slot-scope="{ row }" slot="receive_type">
          <span v-if="row.receive_type === 1">手动领取</span>
          <span v-else-if="row.receive_type === 2">新人券</span>
          <span v-else-if="row.receive_type === 3">赠送券</span>
          <span v-else>会员券</span>
        </template>
        <template slot-scope="{ row }" slot="use_company">
          <span>{{row.use_company}}</span>
        </template>
        <template slot-scope="{ row }" slot="active_status">
          <span v-if="row.active_status === 0 ">未激活 </span>
          <span v-if="row.active_status === 1 ">已激活 </span>
          <span v-if="row.active_status === 2 ">已作废 </span>
        </template>
        <template slot-scope="{ row }" slot="start_end_time">
          <span v-if="row.start_use_time">{{ formatDatefun(row.start_use_time) + '-' +formatDatefun(row.end_use_time) }} </span>
        </template>

        <template slot-scope="{ row }" slot="status">
          <span>{{row.status == 0 ? '未使用' : ''}}{{row.status == 1 ? '已使用' : ''}}{{row.status == -1 ? '已过期' : ''}}</span>
        </template>
        <template slot-scope="{ row }" slot="qrcode">
          <span> <img :src="row.qrcode"></span>
        </template>
        <template slot-scope="{ row }" slot="add_time">
          <span>{{row.add_time}}</span>
        </template>

        <template slot-scope="{ row }" slot="card_no">
          <div v-html="row.card_no"></div>
        </template>
        <template slot-scope="{ row }" slot="uid">
          <div>{{row.uid ? '是' : '否'}}</div>
        </template>
        <template slot-scope="{ row }" slot="action">
          <a @click="deleterow(row)" v-if="row.active_status == 0 || row.active_status == 1 " >作废</a>
          <a v-if="row.active_status ==2 " >已作废</a>
          <a @click="activeOne(row)" style="margin-left:10px;" v-if="row.active_status == 0 ">激活</a>
        </template>
      </Table>
      <div class="acea-row row-right page">
        <Page :total="total" :current="tableFrom.page" show-elevator show-total @on-change="pageChange"
              :page-size="tableFrom.limit"/>
      </div>
    </Card>
    <!-- 单个激活模态框   -->
    <Modal
        v-model="labelShow"
        scrollable
        title="单个提货卡激活"
        :closable="false"
        width="520"
        :footer-hide="true"
    >
      <Form>
        <FormItem label="购买单位名称" label-for="coupon_title">
          <Input
              v-model="formData.use_company"
              placeholder="请输入购买单位名称"
          ></Input>
        </FormItem>
        <FormItem label="卡号有效期" label-for="coupon_title">
          <RadioGroup v-model="formData.recharcard_use_type">
            <Radio :label="1">天数</Radio>
            <Radio :label="2">时间段</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem v-show="formData.recharcard_use_type == 1" label="有效天数">
          <InputNumber
              :min="1"
              :max="100000000"
              v-model="formData.recharcard_use_time"
          ></InputNumber>
          <div class="info">激活后多少天内有效</div>
        </FormItem>
        <FormItem v-show="formData.recharcard_use_type == 2" label="选择有效期限">
          <DatePicker
              :editable="false"
              v-model="time"
              v-width="320"
              type="datetimerange"
              placeholder="激活后在这个时间段内可以使用"
              @on-change="dateChange"
          ></DatePicker>
        </FormItem>
        <div style="width:100%;position:relative;height:30px;">
          <Button type="primary" style="position:absolute;right:70px;" @click="activeSubmit">提交</Button>
          <Button style="position:absolute;right:0px;" @click="labelShow = false">取消</Button>
        </div>
      </Form>
    </Modal>
    <!-- 批量激活模态框   -->
    <Modal
        v-model="activeAllmodals"
        title="批量激活提货卡"
        ok-text="立即激活"
        @on-ok="activeAllRecharcard"
        @on-cancel="cancel">
      <Form :model="formData" :label-width="150" :rules="rules">
        <FormItem label="购买单位名称">
          <Input
              v-model="formData.use_company"
              v-width="320"
              placeholder="请输入购买单位名称"
          ></Input>
        </FormItem>
        <FormItem label="提货卡ID" prop="recharcard_id">
          <Input
              v-model="formData.recharcard_id"
              v-width="320"
              placeholder="请输入要激活的'提货卡ID'"
          ></Input>
        </FormItem>
        <FormItem label="激活卡编号区间">
          <Input
              v-model="formData.start_card_no"
              v-width="140"
              placeholder="请输入激活卡开始编号"
          ></Input>
          ——
          <Input
              v-model="formData.end_card_no"
              v-width="140"
              placeholder="请输入激活卡结束编号"
          ></Input>
          <br>
          <span style="color:red;">激活卡编号请输入带NO.的完整卡编号,Eg:"NO.2022000014"</span>
        </FormItem>
        <FormItem label="有效期">
          <RadioGroup v-model="formData.recharcard_use_type" >
            <Radio :label="1">天数</Radio>
            <Radio :label="2">时间段</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem v-show="formData.recharcard_use_type == 1" label="">
          <InputNumber
              :min="1"
              :max="100000000"
              v-model="formData.recharcard_use_time"
          ></InputNumber>
          <div class="info">激活后多少天内有效</div>
        </FormItem>
        <FormItem v-show="formData.recharcard_use_type == 2" label="">
          <DatePicker
              v-width="320"
              :editable="false"
              v-model="time"
              type="datetimerange"
              placeholder="激活后在这个时间段内可以使用"
              @on-change="dateChange"
          ></DatePicker>
        </FormItem>
      </Form>
    </Modal>
    <!-- 删除模态框   -->
    <Modal
        v-model="modal"
        title="提示"
        @on-ok="recharCardInvalid"
        @on-cancel="cancel">
      <p><span style="color: red;margin: 0 10px;font-weight: bolder;" v-if="this.uid != 0">该提货卡已被领取</span>确定要作废吗?</p>
    </Modal>
  </div>
</template>

<script>
import {
  recharcardUser,
  recharcardActivateOne,
  recharCardInvalid,
  recharcardActivateLst,  // 批量激活
  storeRecharcardUser,  //下载导出
  recharCardList
} from '@/api/user.js'
import exportExcel from "@/utils/newToExcel.js";
import {mapState} from "vuex";
export default {
  name: "list.vue",
  data() {
    return {
      modal:false,      // 删除弹窗模态框
      activeAllmodals:false ,   //批量激活模态框
      labelShow:false,  //单个激活模态框
      id:0,
      rowId:0,
      rules:{   //定义批量激活表单验证
        recharcard_id:[{required: true, message: '请输入提货卡ID', trigger: 'blur'}],
      },
      grid: {
        xl: 7,
        lg: 7,
        md: 12,
        sm: 24,
        xs: 24
      },
      uid:'',
      time:[],
      formData:{
        use_company:'',
        recharcard_use_type:1,
        recharcard_use_time:0,
        recharcard_id :0,
      },
      loading: false,
      recharcard_rule:'',
      columns1: [
        {
          title: "卡号ID",
          key: "id",
          width: 80,
          align:'center'
        },
        {
          title: "提货卡ID",
          key: "recharcard_id",
          width: 40,
          align:'center'
        },
        {
          title: "提货卡名称",
          slot: "recharcard_title",
          minWidth: 180,
          align:'center'
        },
        {
          title: "购买单位名称",
          slot: "use_company",
          minWidth: 120,
          align:'center'
        },
        {
          title: "卡编号",
          slot: "card_no",
          minWidth: 140,
          align:'center'
        },
        {
          title: "序列号",
          slot: "card_serial",
          minWidth: 140,
          align:'center'
        },
        {
          title: "是否领取",
          slot: "uid",
          align:'center',
          minWidth: 80
        },
        {
          title: "提货卡状态",
          slot: "status",
          align:'center',
          minWidth: 80
        },
        {
          title: "是否激活",
          slot: "active_status",
          align:'center',
          minWidth: 100
        },
        {
          title: "有效时间",
          slot: "start_end_time",
          align:'center',
          minWidth: 100
        },
        {
          title: "金额",
          slot: "recharcard_money",
          align:'center',
          minWidth: 80
        },
        {
          title: "二维码",
          slot: "qrcode",
          align:'center',
          minWidth: 120
        },
        {
          title: "创建时间",
          slot: "add_time",
          align:'center',
          minWidth: 160
        },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          align:'center',
          minWidth: 200
        }
      ],
      tableFrom: {
        title :'',
        active_status : '',
        use_company : '',
        start_card_no:'',
        end_card_no:'',
        use_time : '',
        card_serial :'',
        page: 1,
        limit: 15
      },
      receive_type: "",
      tableList: [],
      total: 0,
      FromData: null,
      receiveList: [],
      loading2: false,
      total2: 0,
      receiveFrom: {
        page: 1,
        limit: 15
      },
      rows: {}
    };
  },
  created(){
    this.rowId = this.$route.query.id ? this.$route.query.id : 0
    this.recharCardList(this.rowId)

  },
  computed: {
    ...mapState("admin/layout", ["isMobile"]),
    labelWidth() {
      return this.isMobile ? undefined : 96;
    },
    labelPosition() {
      return this.isMobile ? "top" : "right";
    },
    //格式化有效期的时间字段输出
    formatDatefun() {
      return function(timestamp) {
        const date = new Date(timestamp* 1000);
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2);
        const day = ('0' + date.getDate()).slice(-2);
        const hours = ('0' + date.getHours()).slice(-2);
        const minutes = ('0' + date.getMinutes()).slice(-2);
        const seconds = ('0' + date.getSeconds()).slice(-2);
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      };
    }
  },
  mounted(){
    //  console.log( this.$route.query,111)
  },
  methods:{
    //点击导出列表
    async exportList(){
      let [th, filekey, data, fileName] = [[], [], [], ""];
      let excelData = JSON.parse(JSON.stringify(this.tableFrom));
      excelData.page = 1;
      excelData.product_id= this.$route.query.product_id || "";
      for (let i = 0; i < excelData.page + 1; i++) {
        let lebData = await this.storeRecharcard(excelData);
        if (!fileName) fileName = lebData.filename;
        if (!filekey.length) {
          filekey = lebData.filekey;
        }
        if (!th.length) th = lebData.header;
        if (lebData.export.length) {
          data = data.concat(lebData.export);
          excelData.page++;
        }
      }
      exportExcel(th, filekey, fileName, data);
    },
    storeRecharcard(excelData){
      return new Promise((resolve, reject) => {
        storeRecharcardUser(excelData).then((res) => {
          return resolve(res.data);
        });
      });
    },
    //点击弹出删除模态框
    deleterow(row){
      this.id = row.id
      this.uid = row.uid
      this.modal = true
    },
    //点击激活某一项
    activeOne(row){
      this.id = row.id
      this.formData.use_company = row.use_company
      this.labelShow = true
    },
    //点击批量激活按钮后的提交
    activeAllRecharcard(){
      this.disabled = false
      let rowId = this.formData.recharcard_id
      delete this.formData.recharcard_id;
      recharcardActivateLst(rowId,this.formData).then(res=>{
        this.disabled = true;
        this.$Message.success(res.msg);
        this.recharCardList(0)
        // setTimeout(() => {
        //   this.recharCardList()
        //   this.$router.push({
        //     // path: "/admin/user/recharcard/record?id=" + this.rowId,
        //      path: "/admin/user/recharcard/record",
        //    });
        // }, 1000);
      })
          .catch((err) => {
            this.$Message.error(err.msg);
          });
    },
    //点击显示批量激活模态框
    activeAll(row){
      this.activeAllmodals = true
    },

    //获取年月日时分秒
    getCurrentTime(time) {
      //获取当前时间并打印

      let yy = new Date(time).getFullYear();
      let mm = new Date(time).getMonth()+1;
      let dd = new Date(time).getDate();
      let hh = new Date(time).getHours();
      let mf = new Date(time).getMinutes()<10 ? '0'+new Date(time).getMinutes() : new Date(time).getMinutes();
      let ss = new Date(time).getSeconds()<10 ? '0'+new Date(time).getSeconds() : new Date(time).getSeconds();
      return yy+'-'+mm+'-'+dd+' '+hh+':'+mf+':'+ss;
    },

    //分页
    pageChange(e){
      this.tableFrom.page = e
      this.recharCardList(this.rowId)
    },
    /**
     * 作废提货卡
     */
    recharCardInvalid(){
      recharCardInvalid(this.id).then(res=>{
        this.$Message.success(res.msg);
        this.modal = false
        this.recharCardList(this.rowId)
      })
          .catch((err) => {
            this.$Message.error(err.msg);
          });
    },
    //关闭模态框
    cancel(){
      this.modal = false
    },

    //补零
    fillZero (str) {
      var realNum;
      if (str < 10) {
        realNum = '0' + str;
      } else {
        realNum = str;
      }
      return realNum;
    },
    getNowTime(time) {
      let now = new Date(time);
      let year = now.getFullYear(); //获取完整的年份(4位,1970-????)
      let month = now.getMonth() + 1; //获取当前月份(0-11,0代表1月)
      let today = now.getDate(); //获取当前日(1-31)
      let hour = now.getHours(); //获取当前小时数(0-23)
      let minute = now.getMinutes(); //获取当前分钟数(0-59)
      let second = now.getSeconds(); //获取当前秒数(0-59)
      let nowTime = ''
      nowTime = year + '/' + this.fillZero(month) + '/' + this.fillZero(today) + ' ' + this.fillZero(hour) + ':' +
          this.fillZero(minute) + ':' + this.fillZero(second)
      return nowTime
    },
    /**
     * 激活时间区间处理
     * 使用有效期--时间段
     * @param time
     */
    dateChange(time) {
      var date1 = this.getNowTime(time[0])
      var date2 = this.getNowTime(time[1])
      if(new Date(time[0]).getTime() == new Date(time[1]).getTime()){
        this.time = []
        return this.$Message.error("所选时间不能相同");
      }
      if(new Date(time[0]).getTime() > new Date(time[1]).getTime()){
        this.formData.recharcard_use_time = date2 + '-' + date1
      }else{
        this.formData.recharcard_use_time = date1 + '-' + date2
      }
    },
    //点击修改
    activeSubmit(){
      recharcardActivateOne(this.id,this.formData).then(res=>{
        this.$Message.success(res.msg);
        this.labelShow = false
        this.recharCardList(this.rowId)
      })
          .catch(err => {
            this.$Message.error(err.msg);
          })
    },
    //充值卡激活--列表
    recharCardList(id){
      recharcardUser(id,this.tableFrom).then(res=>{
        this.tableList = res.data.list
        console.log('recharcardList',this.tableList)
        this.tableList.forEach(item=>{
          item.add_time = this.getCurrentTime((item.add_time * 1000))
        })
        this.total = res.data.count
      })
    },
    // 表格搜索
    userSearchs() {
      this.tableFrom.page = 1;
      this.recharCardList();
    },
    /**
     * 提货卡搜素
     */
    orderSearch(){
      if(this.tableFrom.start_card_no != '' && this.tableFrom.end_card_no == ''){
        return this.$Message.error('请填写提货卡的结束编号')
      }else if(this.tableFrom.start_card_no == '' && this.tableFrom.end_card_no != ''){
        return this.$Message.error('请填写提货卡的开始编号')
      }
      this.recharCardList(this.rowId)
    }
  }
}
</script>


<style scoped lang="stylus">
.fa {
  color: #0a6aa1;
  display: block;
}

.sheng {
  color: #ff0000;
  display: block;
}

.tabBox_img {
  width: 36px;
  height: 36px;
  border-radius: 4px;
  cursor: pointer;
}
img {
  width: 100%;
  height: 100%;
}

</style>
